package com.cskaoyan.mall.common.config;

import lombok.Data;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.codec.JsonJacksonCodec;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

/**
 * redisson配置信息
 * 谁依赖我，就使用谁的配置
 */
@Data
@Configuration
@ConfigurationProperties(prefix = "spring.redis") //和下面所有@Value效果一样
public class RedissonConfig {

    //@Value("${spring.redis.host}") //从配置文件中取值
    private String host;

    //@Value("${spring.redis.addresses}")  //从配置文件中取值
    private String addresses;

    private String password;

    private String port;

    private int timeout = 5000;
    private int connectionPoolSize = 64;
    private int connectionMinimumIdleSize=10;
    private int pingConnectionInterval = 60000;
    private static String PROTOCAL = "redis://";

    /**
     * 自动装配
     */
    @Bean
    RedissonClient redissonSingle() {
        Config config = new Config();
        if(StringUtils.isEmpty(host)){
            throw new RuntimeException("host is empty");
        }
        SingleServerConfig serverConfig = config.useSingleServer()
                //redis://127.0.0.1:7181
                .setAddress(PROTOCAL + this.host + ":" + port)
                .setTimeout(this.timeout)   //都是默认配置
                .setPingConnectionInterval(pingConnectionInterval)
                .setConnectionPoolSize(this.connectionPoolSize)
                .setConnectionMinimumIdleSize(this.connectionMinimumIdleSize);
        if(!StringUtils.isEmpty(this.password)) {
            serverConfig.setPassword(this.password);
        }

        // 设置序列化
        config.setCodec(new JsonJacksonCodec());

        return Redisson.create(config);
    }
}
